package com.example.demo.utils;

import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

/*
 上传文件处理工具类
 */
public class FileUtils {

    // 上传路径
    private final String uploadDir = Paths.get("C://uploads//userinfo").toString();

    public String uploadFile(MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            throw new IllegalArgumentException("上传文件不能为空");
        }
        // 生成唯一文件名
        String fileName = UUID.randomUUID() +
                "." + StringUtils.getFilenameExtension(file.getOriginalFilename());

        // 创建存储目录（如果不存在）
        Path uploadPath = Paths.get(uploadDir);
        if (!Files.exists(uploadPath)) {
            Files.createDirectories(uploadPath);
        }
        // 保存文件
        Path filePath = uploadPath.resolve(fileName);
        file.transferTo(filePath.toFile());
        // 返回访问URL
        // 在线路径前缀
        String baseUrl = "http://localhost:8080/uploads";
        return baseUrl + "/" + fileName;
    }
}
